<?php

namespace App\Services\Pay\GuoTonXinYi;


use App\Api\Controllers\Config\PayWaysController;
use App\Api\Controllers\Merchant\PayBaseController;
use App\Exceptions\BizException;
use App\Models\Merchant;
use App\Models\Order;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\UserRate;
use App\Services\Pay\ResultVo;
use Illuminate\Support\Facades\Log;
use function EasyWeChat\Kernel\Support\get_client_ip;

class Pay
{
    //支付用到 得到成本费率  通过ways_type查询
    public static function getCostRate($ways_type, $user_id)
    {
        $user_rate_obj = UserRate::where('ways_type', $ways_type)
            ->where('user_id', $user_id)
            ->where('status', 1)
            ->orderby('created_at', 'desc')
            ->first();

        return $user_rate_obj;
    }

    public static function embedPay(array $data, array $config): ResultVo
    {
        try {
            $response = [
                "AGET_ID" => $config["agetId"],
                "CUST_ID" => $data["custId"],
                "THREE_ORDER_NO" => $data["orderNo"],
                "TxnAmt" => $data["total_amount"],//订单金额 单位分$data["txamt"],
                "ACCESS_TYPE" => "02",
                "PAY_WAY" => "8", "interface" => "000002",
                "timeStamp" => date("YmdHis", time()),
                "ASYNC_NOTIFY_IP" => env("APP_URL") . "/api/gtxy/pay_notify_url",
            ];
            $store = Store::query()->where("store_id", $data["store_id"])->first();
            if (empty($store)) {
                throw new BizException("门店不存在");
            }
            //关闭的商户禁止交易
            if ($store->is_close || $store->is_admin_close || $store->is_delete || $store->state == 3) {
                throw  new BizException("商户已经关闭");
            }
            if ($store->status != 1) {
                throw  new BizException("商户已经关闭");
            }
            list($isRun, $error) = \App\Services\Store\StoreSignService::validateSign((string)$store->store_id, (string)$data["company"]);
            if ($isRun == false) {
                throw new BizException($error);
            }

            $merchant = Merchant::query()->find($data["merchant_id"]);
            if (empty($merchant)) {
                throw new BizException("收银员不存在");
            }
            //插入数据库
            $data_insert = [
                'trade_no' => '',
                'user_id' => $store->user_id,
                'store_id' => $store->store_id,
                'store_name' => $store->store_id,
                'buyer_id' => '',
                'total_amount' => $data["total_amount"],
                'shop_price' => $data["total_amount"],
                'payment_method' => '',
                'status' => '',
                'pay_status' => 2,
                'pay_status_desc' => '等待支付',
                'merchant_id' => empty($merchant) ? 0 : $merchant->id,
                'merchant_name' => empty($merchant) ? "" : $merchant->name,
                'remark' => "",
                'device_id' => "",
                'config_id' => "1234",
                'other_no' => "",
                'pay_method' => "embedPay",
                "notify_url" => $data["notify_url"] ?? ""
            ];

            $ways = StorePayWay::query()
                ->where("status", 1)
                ->where("store_id", $store->store_id)
                ->where("company", $data["company"])
                ->where("ways_source", $data["ways_source"])->first();
            if (empty($ways)) {
                $storeP = Store::query()->where("id", $store->pid)->first();
                if (empty($storeP)) {
                    throw new BizException("主店不存在");
                }
                $ways = StorePayWay::query()
                    ->where("status", 1)
                    ->where("store_id", $storeP->store_id)
                    ->where("company", $data["company"])
                    ->where("ways_source", $data["ways_source"])->first();
            }
            if (empty($ways)) {
                throw new BizException("支付方式不存在");
            }

            $user_rate_obj = self::getCostRate($ways->ways_type, $store->user_id);
            $cost_rate = $user_rate_obj ? $user_rate_obj->rate : 0.00; //成本费率
            //扫码费率入库
            if ($cost_rate) $data_insert['cost_rate'] = $cost_rate;
            $data_insert['rate'] = $ways->rate;
            $data_insert['fee_amount'] = $ways->rate * $data["total_amount"] / 100;


            $ways_source_desc = "";
            switch ($data['ways_source']) {
                case "weixin":
                    $ways_source_desc = "微信支付";
                    break;
                case "alipay":
                    $ways_source_desc = "支付宝";
                    break;
                case "unionpay":
                    $ways_source_desc = "云闪付";
                    break;
            }

            //入库参数
            $data_insert['out_trade_no'] = $data["orderNo"];
            $data_insert['ways_type'] = $ways->ways_type;
            $data_insert['ways_type_desc'] = $ways->ways_desc;
            $data_insert['ways_source'] = $data['ways_source'];
            $data_insert['company'] = $data['company'];
            $data_insert['ways_source_desc'] = $ways_source_desc;
            $data_insert['other_no'] = $data['other_no'] ?? "";
            $insert_re = (new PayBaseController())->insert_day_order($data_insert);
            if (empty($insert_re)) {
                throw new BizException("订单写入失败");
            }
            $resultVo = ResultVo::code("ok")::data($response)::msg("ok");
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }

    public static function embedQuery(array $data, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::EmbedUrl;
            $reqData = [
                "agetId" => $config["agetId"],
                "custId" => $data["custId"],
                "sceneType" => $data["sceneType"],
                "orderNo" => $data["orderNo"],
                "txamt" => bcmul((string)$data["txamt"], (string)100),//订单金额 单位分$data["txamt"],
                "remark" => $data["remark"] ?? "",
                "asyncNotify" => $data["asyncNotify"] ?? "",
                "version" => Config::VERSION,
                "timeStamp" => date("YmdHis", time()),
            ];
            $reqData["sign"] = Config::getSign($reqData, $config["public_key"]);
            $resultArray = Config::post($url, $reqData);
            Log::channel("gtxy")->info("embed", [
                "url" => $url,
                "reqData" => $reqData,
                "resData" => $resultArray
            ]);
            if (empty($resultArray) || !isset($resultArray["code"]) || $resultArray["code"] != "000000") {
                throw new BizException("响应异常");
            }
            $response = [
                "urlScheme" => $resultArray["data"]["urlScheme"] ?? "",
                "appid" => $resultArray["data"]["appid"] ?? "",
                "path" => $resultArray["data"]["path"] ?? ""
            ];
            $resultVo = ResultVo::code("ok")::data($response)::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


    //yyfsevr/order/pay
    //统一下单接口  C->B   暂时不使用-这个需要借助自己的平台，来判断到底是什么支付方式
    public static function pay(string $order_no, array $data, array $config): ResultVo
    {
        try {


            $url = Config::getDomain() . Config::pay;
            $reqData = [
                "agetId" => $config["platform_id"],
                "custId" => $config["mch_no"],
                "orderNo" => $order_no,//服务商订单号（第三方订单号）
                "txamt" => bcmul((string)$data["total_amount"], "100"),//订单金额 单位分
                "openid" => "",//根据微信、支付宝、银联给出的官方文档获取，微信是openid，支付宝是userId（以 2088 开头），银联用户标识看前往对接前准备-“获取银联用户标识”接口获取
                "payWay" => $data["payWay"],//1.微信支付（小程序） 2.支付宝支付 3.银联支付
                "ip" => $data["ip"] ?? get_client_ip(),
                "timeStamp" => (string)time(),
                "version" => Config::VERSION,
//            "title" => "",//订单标题
//            "driveNo" => "",//自定义设备号
//            "wxAppid" => "",//微信支付必传
//            "traType" => "",//微信支付必传，5公众号 8小程序。（京东白条可传，因白条是基于微信公众号或小程序来跳转白条支付的，未传默认为公众号）
//            "limitPay" => "",//微信支付，0-无限制，1-不能使用信用卡
//            "zfbappid" => "",//支付宝appid
//            "zfbDisablePayChannels" => "",//支付宝禁用支付渠道
//            "qrCode" => "",//交易二维码链接
//            "qrCodeType"=>"",//交易二维码类型
            ];
            $sign = Config::getSign($reqData, $config["public_key"]);

            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("error")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


    /**
     * 商户主扫（B扫C）
     *
     */
    /**
     * $goods=[
     * "cost_price"=>0, //单位分   total_amount*100
     * "receipt_id"=>"",
     * "goods_detail"=>[
     *  [
     * "goods_id"=>"",
     * "price"=>"",
     * "quantity"=>"",
     * "goods_name"=>""
     * ]
     * ]
     * ];
     */

    /**
     * $params=[
     *  "pay_method",
     *  "total_amount",
     *  "store_address"，
     * ];
     */

    /**
     * B->C
     * @param string $order_no
     * @param string $code
     * @param string $ways_source
     * @param array $params
     * @param array $goods
     * @return ResultVo
     */
    public static function scanByMerchant(array $config, string $out_trade_no, array $params, string $goods): ResultVo
    {
        try {
            $code = $params["code"];
            $ways_source = $params["ways_source"];
            //根据支付方式，来设置单品优惠参数
            switch ($params["pay_method"] ?? "") {
                case "scan":
                    $type = "A";
                    break;
                default:
                    $type = "A";
            }

            $url = Config::getDomain() . Config::scanByMerchant;
            $reqData = [
                "agetId" => $config["agetId"],
                "custId" => $config["custId"],
                "orderNo" => $out_trade_no,//服务商订单号（第三方订单号）
                "txamt" => bcmul((string)$params["total_amount"], (string)100),//订单金额 单位分
                "code" => $code, //	扫码支付授权码
                "tradingIp" => get_client_ip(),//	交易ip
                "type" => $type, //P-智能POS A- app扫码 C-PC端 T-台牌扫码
                "version" => Config::VERSION,
                "timeStamp" => date("YmdHis", time())
//            "title" => "",//订单标题
//            "driveNo" => "",//自定义设备号
//            "wxAppid" => "",//微信支付必传
//            "traType" => "",//微信支付必传，5公众号 8小程序。（京东白条可传，因白条是基于微信公众号或小程序来跳转白条支付的，未传默认为公众号）
//            "limitPay" => "",//微信支付，0-无限制，1-不能使用信用卡
//            "zfbappid" => "",//支付宝appid
//            "zfbDisablePayChannels" => "",//支付宝禁用支付渠道
//            "qrCode" => "",//交易二维码链接
//            "qrCodeType"=>"",//交易二维码类型
            ];
            $goods = json_decode($goods, true);
            $goods_detail = $goods["goods_detail"] ?? [];
            //设置单品信息
            switch ($ways_source) {
                case "weixin":
                    $goods_detail_entity = [];
                    foreach ($goods_detail as $v) {
                        $goods_detail_entity[] = [
                            'quantity' => $v['quantity'],
                            'goods_id' => $v['goods_id'],
                            'wxpay_goods_id' => $v['goods_id'],
                            'price' => (int)$v['price'] * 100,
                            'goods_name' => $v['goods_name'],
                        ];
                    }
                    if (!empty($goods_detail_entity)) {
                        $reqData["detail"] = [
                            "receipt_id" => (string)$goods["receipt_id"],//商家小票ID
                            "cost_price" => $goods["cost_price"],//单位分
                            "goods_detail" => $goods_detail_entity
                        ];
                    }
                    break;
                case "alipay":
                    $quantity = 0;
                    foreach ($goods_detail as $v) {
                        $quantity += $v['quantity'];
                        $goods_detail_entity = [
                            'goods_id' => (string)$v['goods_id'],
                            'goods_name' => $v['goods_name'],
                        ];
                    }
                    if (!empty($quantity)) {
                        $reqData["goodsDetail"] = [
                            "goods_id" => (string)$goods_detail_entity["goods_id"],
                            "goods_name" => $goods_detail_entity["goods_name"],
                            "quantity" => $quantity,
                            "price" => $goods["cost_price"],
                        ];
                    }
                    break;
                case "unionpay":
                    $goods_detail_entity = [];
                    foreach ($goods_detail as $v) {
                        $goods_detail_entity[] = [
                            'id' => (string)$v['goods_id'],
                            "name" => $v["goods_name"],
                            "price" => (int)$v['price'] * 100,
                            'quantity' => $v['quantity'],
                        ];
                    }
                    if (!empty($goods_detail_entity)) {
                        $reqData["acqAddnData"] = [
                            "goodsInfo" => $goods_detail_entity,
                            "orderInfo" => [
                                "title" => $goods_detail_entity["name"] ?? "",
                                "dctAmount" => $params["total_amount"] * 100,
                                "addnInfo" => $params["store_address"] ?? ""
                            ]
                        ];
                    }
                    break;
                default:
                    throw new \Exception("支付方式不支持");
            }
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            //写入日志
            Log::channel("gtxy")->info("res-and-req", [
                "url" => $url,
                "req" => $reqData,
                "res" => $resultArray
            ]);
            if (empty($resultArray) || !isset($resultArray["code"])) {
                throw new \RuntimeException("响应异常");
            }
            //            {"msg":"支付中","code":"222222","data":{"agetId":"61000000339654","orderNo":"20250326SS1r2qbe","orderTime":"20250326143701","threeOrderNo":"20250326143702455694662","tradingIp":"117.64.87.96","torderNo":"20250326143938047578","txamt":"1"}}
            switch ($resultArray["code"]) {
                case ResultVo::GtxyResponseCodeMap["ok"]:
                    $pay_status = 1;
                    break;
                case  ResultVo::GtxyResponseCodeMap["paying"]:
                    $pay_status = 2;
                    break;
                case ResultVo::GtxyResponseCodeMap["payfail"]:
                    $pay_status = 3;
                    break;
                default:
                    throw new \Exception("支付异常请联系管理人员:" . $resultArray["msg"] ?? "");
            }
            $response = [
                "pay_status" => $pay_status,
                "out_trade_no" => $out_trade_no,
                "other_no" => $resultArray["data"]["orderNo"] ?? "",//orderNo国通平台订单号
                'trade_no' => $resultArray["data"]["payNo"] ?? "",//torderNo 微信/支付宝（目的通道流水号），银联（官方订单号）可用于退款
                "custFee" => $resultArray["data"]["custFee"] ?? "", //商户交易实收手续费
                "oldFee" => $resultArray["data"]["oldFee"] ?? "",//应收手续费
                "pay_time" => $resultArray["data"]["orderTime"] ?? "",//订单完成时间 yyyyMMddHHmmss
                "cardType" => $resultArray["data"]["cardType"] ?? "0",//01借记卡、 02贷记卡、03其他
                "promotionDetail" => $resultArray["data"]["promotionDetail"] ?? "",
                "openId" => $resultArray["data"]["openId"] ?? "",
            ];
            $resultVo = ResultVo::code("ok")::data($response)::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            if ($e instanceof \RuntimeException) {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
            } else {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage());
            }
            Log::channel("gtxy")->info("error-" . $out_trade_no, [
                "out_trade_no" => $out_trade_no,
                "res" => $resultVo->getMsg()
            ]);
        }
        return $resultVo;
    }


    ///yyfsevr/order/orderQuery
    /// 交易查询接口（全部）
    public static function orderQuery($order, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::orderQuery;
            $reqData = [
                "agetId" => $config["agetId"],
                "custId" => $config["custId"],
                "orderNo" => $order->out_trade_no, //服务商订单号与国通订单号二选一
                "tradingIp" => get_client_ip(),//	交易ip
                "orderTime" => date("Ymd", strtotime($order->pay_time)),//格式yyyyMMdd
                "timeStamp" => date("YmdHis", time()),
                "version" => Config::VERSION
            ];
            $reqData["sign"] = Config::getSign($reqData, $config["public_key"]);
            $resultArray = Config::post($url, $reqData);
            Log::channel("gtxy")->info("orderQuery", [
                "reqData" => $reqData,
                "resData" => $resultArray
            ]);
            if (empty($resultArray) || !isset($resultArray["code"])) {
                throw new \RuntimeException("响应异常");
            }
            switch ($resultArray["code"]) {
                case ResultVo::GtxyResponseCodeMap["ok"]:
                    $pay_status = 1;
                    break;
                case ResultVo::GtxyResponseCodeMap["paying"]:
                    $pay_status = 2;
                    break;
                case ResultVo::GtxyResponseCodeMap["payfail"]:
                case ResultVo::GtxyResponseCodeMap["paycancel"]:
                case ResultVo::GtxyResponseCodeMap["payclose"]:
                    $pay_status = 3;
                    break;
                default:
                    throw new \Exception("支付异常请联系管理人员");
            }
            $response = [
                "pay_status" => $pay_status,
                "out_trade_no" => $order->out_trade_no,
                "other_no" => $resultArray["data"]["orderNo"] ?? "",//orderNo国通平台订单号  退款使用
                'trade_no' => $resultArray["data"]["payNo"] ?? "",//torderNo 微信/支付宝（目的通道流水号），银联（官方订单号）可用于退款
                "custFee" => $resultArray["data"]["custFee"] ?? 0, //商户交易实收手续费
                "oldFee" => $resultArray["data"]["oldFee"] ?? 0,//应收手续费
                "pay_time" => $resultArray["data"]["orderTime"] ?? "",//订单完成时间 yyyyMMddHHmmss
                "cardType" => $resultArray["data"]["cardType"] ?? "00",//01借记卡、 02贷记卡、03其他
                "netrAmt" => $resultArray["data"]["netrAmt"] ?? "",
                "promotionDetail" => $resultArray["data"]["promotionDetail"] ?? "",
                "openId" => $resultArray["data"]["openId"] ?? "",
            ];
            $resultVo = ResultVo::code("ok")::data($response)::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            if ($e instanceof \RuntimeException) {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
            } else {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage());
            }
        }
        return $resultVo;
    }

    /**
     * 退款计算公式
     * 部分退款手续费 算法如下：
     * a. 先算出 退款金额比率=退款金额/原交易金额（四舍五入保留小数点后10位）
     * b. 退款手续费= 原订单手续费*退款金额比率（单位精确分小数后不保留）
     * c.如退款金额为最后一笔对应退款取剩余退款手续费
     *
     * 全额退款手续费取原手续费
     *
     * 退款
     * @return void
     */
    public static function refund(Order $order, float $refund_amount, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::refund;
            switch ($order->ways_source) {
                case "weixin":
                    $tag = 2;
                    break;
                case "alipay":
                    $tag = 1;
                    break;
                case "unionpay":
                    $tag = 9;
                    break;
                default:
                    $tag = 9;
            }
            $reqData = [
                "agetId" => $config["agetId"],
                "custId" => $config["custId"],
                "timeStamp" => date("YmdHis", time()),
                "version" => Config::VERSION,
                "orderNo" => $order->out_trade_no . rand(10000, 99999),//第三方退款订单号，该订单号需要唯一，最大长度40，只能由数字，大小写字母构成（合作方重新生成的一个用来退款的订单号）。对应星POS：tradeNo
                "reOrderNo" => empty($order->trade_no) ? $order->out_trade_no : $order->trade_no,//other_no 国通平台订单号（国通平台订单号，官方退款订单号，原第三方交易订单号三选一）
                "refundAmount" => bcmul((string)$refund_amount, (string)100),//单位分
                "tag" => $tag,//1支付宝 2微信 9银联（类型必须填写正确，与正向交易订单类型一致）12数币支付
            ];

            $reqData["sign"] = Config::getSign($reqData, $config["public_key"]);

            $resultArray = Config::post($url, $reqData);
            Log::channel("gtxy")->info("orderRefund", [
                "url" => $url,
                "reqData" => $reqData,
                "resData" => $resultArray
            ]);
            if (empty($resultArray) || !isset($resultArray["code"])) {
                throw new \RuntimeException("响应异常");
            }
            switch ($resultArray["code"]) {
                case ResultVo::GtxyResponseCodeMap["ok"]:
                    //通讯成功
                    if (!isset($resultArray["data"]["orderStatus"])) {
                        throw new \RuntimeException("退款异常，请联系管理员");
                    }
//                    3退款失败 4退款成功 5退款中
                    if ($resultArray["data"]["orderStatus"] == 3) {
                        $pay_status = 8;//退款失败
                    } else if ($resultArray["data"]["orderStatus"] == 4) {
                        $pay_status = 6; //退款成功
                    } else if ($resultArray["data"]["orderStatus"] == 5) {
                        $pay_status = 7; //退款中
                    }
                    break;
                default:
                    throw new \RuntimeException("退款异常，请联系管理员");
            }
            $response = [
                'pay_status' => $pay_status,
                'pay_status_desc' => '已退款',
                'refund_amount' => $resultArray["data"]["refundAmt"] / 100,
                "refund_no" => $resultArray["data"]["orderFlowNo"] ?? "",//orderFlowNo
                "trade_no" => $resultArray["data"]["orderFlowNo"] ?? "",//orderFlowNo
            ];
            $resultVo = ResultVo::code()::data($response)::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            if ($e instanceof \RuntimeException) {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
            } else {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage());
            }
        }
        return $resultVo;
    }


    //退款查询
    public static function refundQuery(string $refund_no, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::refundQuery;
            $reqData = [
                "orderNo" => $refund_no,//服务商退款的时候上送的退款订单号。 对应星POS：tradeNo
                "agetId" => $config["agetId"],
                "custId" => $config["custId"],
                "timeStamp" => date("YmdHis", time()),
                "version" => Config::VERSION,
            ];

            $reqData["sign"] = Config::getSign($reqData, $config["public_key"]);

            $resultArray = Config::post($url, $reqData);

            if (empty($resultArray) || !isset($resultArray["code"])) {
                throw new \RuntimeException("响应异常");
            }
//            000000 表示成功，121336 第三方订单信息不存在，121338 该订单还未退款，请稍后查询，121337 该订单已关闭请重新发起新退款订单，333333 退款失败，000002 查找退款订单失败，
//000002 退款状态查询仅支持当天
            switch ($resultArray["code"]) {
                case ResultVo::GtxyResponseCodeMap["ok"]:

                    if ($resultArray["data"]["orderStatus"] == 4) {
//                        3退款失败 4退款成功 5退款中 7刷卡撤销成功 98刷卡撤销中
                        $pay_status = 6;
                    } else if ($resultArray["data"]["orderStatus"] == 5) {
                        $pay_status = 7;
                    } else if ($resultArray["data"]["orderStatus"] == 3) {
                        $pay_status = 8;
                    }
                    break;
                case ResultVo::GtxyResponseCodeMap["refundfail"]:
                    $pay_status = 8;
                    break;
                case ResultVo::GtxyResponseCodeMap["refunding"]:
                    $pay_status = 7;
                    break;
                case ResultVo::GtxyResponseCodeMap["order_not_exists"]:
                    throw new \RuntimeException("订单不存在");
                case ResultVo::GtxyResponseCodeMap["refundtoday"]:
                    throw new \RuntimeException("只能查询当天的退款");
                default:
                    throw new \RuntimeException("退款查询异常");
            }
            $response = [
                "pay_status" => $pay_status,
                "other_refund_no" => $resultArray["data"]["orderFlowNo"] ?? "",
                "refund_detail" => "",
                "refund_time" => $resultArray["data"]["orderTime"] ?? ""
            ];
            $resultVo = ResultVo::code()::msg($resultArray["msg"])::data($response);
        } catch (\Exception $e) {
            if ($e instanceof \RuntimeException) {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
            } else {
                $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage());
            }
        }
        return $resultVo;
    }


    /*
     * C->B  生成马牌二维码
     */
    public static function getCodeUrl(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::getCodeUrl;
            $reqData = [
                "agetId" => $config["agetId"],
                "custId" => $config["custId"],
                "orderNo" => $params["orderNo"],//用于调用查询接口时，写入服务商订单号（第三方订单号）使用
                "txamt" => $params["txamt"],//分
                "payType" => "00",
//                00确认支付、01直接支付。00确认支付(唤起国通收银台查看金额信息，填写备注信息后点击支付完成交易，当接口备注与收银台填写备注不一致时，默认取收银台填写备注进行覆盖)、01直接支付 (未打开国通收银台，直接唤起支付)，未传默认上送00支付确认
                "version" => Config::VERSION,
                "asyncNotify" => url("/api/gtxy/pay_notify_url"),
//                "notifyUrl" => url('/api/cmbc/pay_notify_url').'?mch_id='.$merchant->mch_id
                "timeStamp" => date("YmdHis", time()),
            ];

            $sign = Config::getSign($reqData, $config["public_key"]);

            $reqData["sign"] = $sign;

            $resultArray = Config::post($url, $reqData);

            if (empty($resultArray) || !isset($resultArray["code"])) {
                throw new \RuntimeException("响应参数错误");
            }
            Log::channel("gtxy")->info("getCodeUrl", [
                "url" => $url,
                "req" => $reqData,
                "res" => $resultArray
            ]);
            if ($resultArray["code"] != ResultVo::GtxyResponseCodeMap["ok"]) {
                throw new \RuntimeException($resultArray["msg"] ?? "响应异常");
            }
            $response = [
                "url" => $resultArray["data"] ?? ""
            ];
            $resultVo = ResultVo::code()::data($response)::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage());
        }
        return $resultVo;
    }

    public static function queryLimit(string $mch_no, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::queryLimit;
            $reqData = [
                "agetId" => $config["platform_id"],
                "custId" => $mch_no,
                "timeStamp" => date("YmdHis", time()),
                "version" => Config::VERSION,
            ];
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            if (empty($resultArray) || !isset($resultArray["code"])) {
                throw new \RuntimeException("响应参数错误");
            }
            Log::channel("gtxy")->info("queryLimit", [
                "req" => $reqData,
                "res" => $resultArray
            ]);
            if ($resultArray["code"] != ResultVo::GtxyResponseCodeMap["ok"]) {
                throw new \RuntimeException($resultArray["msg"]);
            }
            $response = [
                "type" => $resultArray["data"]["type"],
                "balanceTxamt" => $resultArray["data"]["balanceTxamt"],
                "time" => $resultArray["data"]["time"],
                "clearAmt" => $resultArray["data"]["clearAmt"]
            ];
            $resultVo = ResultVo::code()::data($response)::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage());
        }
        return $resultVo;
    }

}